package ngames.com.sushitv.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import ngames.com.sushitv.R;
import ngames.com.sushitv.base.BaseActivity;
import ngames.com.sushitv.tools.AppUtil;
import ngames.com.sushitv.tools.PreferenceManager;

public class WelcomeActivity extends BaseActivity {
    private static final int SLEEP_TIME = 2000;
    private static final int WHAT_SLEEP = 0;
    private static final int WHAT_LOGIC_TO = 1;

    private static final int LOGIC_TO_LOGIN = 1;
    private static final int LOGIC_TO_MAIN = 2;

    private boolean mCheckSleep = false;
    private int mLogicTo = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        TextView versionTv = (TextView) findViewById(R.id.tex_version);
        versionTv.setText(getString(R.string.version, AppUtil.getAppVersionName(this)));
        mHandler.sendEmptyMessageDelayed(WHAT_SLEEP, SLEEP_TIME);
        checkUpdateVersion();
    }

    @Override
    protected void onStop() {
        super.onStop();
        PreferenceManager.getInstance().setHaveOpenApp();
    }

    private void checkUpdateVersion() {
        isFirstOpenApp();
    }

    private void isFirstOpenApp() {
        if (PreferenceManager.getInstance().isFirstOpenApp()) {
            //首次登陆设置，暂时没做处理
            isLogin();
        } else {
            isLogin();
        }
    }

    private void isLogin() {
        if (getAppModel().getUserService().needLogin(false)) {
            //登陆过期，未登录
            mLogicTo = LOGIC_TO_LOGIN;
        } else {
            mLogicTo = LOGIC_TO_LOGIN;
//            mLogicTo = LOGIC_TO_MAIN;
        }
        mHandler.sendEmptyMessage(WHAT_LOGIC_TO);
    }

    private void logicTo(int next) {
        switch (next) {
            case LOGIC_TO_LOGIN:
                startActivity(new Intent(this, LoginActivity.class));
                finish();
                break;
            case LOGIC_TO_MAIN:
                startActivity(new Intent(this, MainActivity.class));
                finish();
                break;
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case WHAT_SLEEP:
                    mCheckSleep = true;
                    logicTo(mLogicTo);
                    break;
                case WHAT_LOGIC_TO:
                    if (mCheckSleep) {
                        logicTo(mLogicTo);
                    }
                    break;
            }
        }
    };
}
